package com.bz.common;

import java.io.Serializable;
import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;

@Component
@RefreshScope
public class JwtTokenUtil implements Serializable {
    private static final long serialVersionUID = -2550185165626007488L;

    // token有效期
    @Value("${jwt.validity}")
    private Long              tokenValidity;

    // 加密秘钥
    @Value("${jwt.secret}")
    private String            secret;

    /**
     * 生成签名
     * 
     * @param userName
     * @return
     */
    public String sign(String userName) {
        Date date = new Date(System.currentTimeMillis() + tokenValidity);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
            // 将 user id 保存到 token 里面
            .withAudience(userName)
            // 五分钟后token过期
            .withExpiresAt(date)
            // token 的密钥
            .sign(algorithm);
    }

    /**
     * 根据token获取userName
     * 
     * @param token
     * @return
     */
    public String getUsername(String token) {
        String username = JWT.decode(token).getAudience().get(0);
        return username;
    }

    /**
     * 校验token
     * 
     * @param token
     * @return
     */
    public boolean checkSign(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                .build();
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException exception) {
            return false;
        }
    }

    public static void main(String[] args) {

        String username = "openid";

        // 五分钟
        Date date = new Date(System.currentTimeMillis() + 1000 * 60 * 60*24 *100);
        Algorithm algorithm = Algorithm.HMAC256("tuososdpofispodifaposif");
        String s = JWT.create()
            // 将 user id 保存到 token 里面
            .withAudience(username)
            // 五分钟后token过期
            .withExpiresAt(date)
            // token 的密钥
            .sign(algorithm);
        System.out.println(s);

    }
}
